import os
from web.models import Video
from django.shortcuts import render
from django.http import FileResponse


def video_stream(request, video_id):
    """流式传输"""
    video = Video.objects.get(id=video_id)
    file_path = video.video_file.path
    file_size = os.path.getsize(file_path)

    # 支持 Range 请求（允许跳转播放）
    range_header = request.headers.get('Range', '').strip()
    if range_header:
        # 处理范围请求（代码简化版，实际需完整实现）
        return FileResponse(open(file_path, 'rb'), content_type='video/mp4')
    else:
        response = FileResponse(open(file_path, 'rb'), content_type='video/mp4')
        response['Content-Length'] = file_size
        response['Accept-Ranges'] = 'bytes'
        return response


def index(request):
    """主页"""
    video = Video.objects.order_by("-add_time").first()
    return render(request, "index.html", {
        "video": video,
    })
